package com.installtime.demo.controller;

import cn.hutool.core.img.Img;
import cn.hutool.core.img.ImgUtil;
import com.installtime.demo.Interceptor.validator.TestUploadValidator;
import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;

/**
 * @Classname TestController
 * @Description TODO
 * @Date 6/29/2020 11:40 AM
 * @Created by W.Z
 */
public class TestController extends Controller {

    private static final int START_WIDTH=600;
    public String test(){

        return "----------------------ssssssssssssssssssssssssssssss-------------------------------------";
    }

    @Before(TestUploadValidator.class)
    public void upload() throws IOException {
        String filePath = getPara("filePath");
        FileInputStream imageInputStream = new FileInputStream(new File(filePath));
        Image img = Img.from(imageInputStream).getImg();
        //原图大小
        int imgWidth = img.getWidth(null);
        int imgHeight = img.getHeight(null);

        int divisor = imgWidth / START_WIDTH;
        divisor=divisor==0?1:divisor;
        Image imageScale = ImgUtil.scale(img, START_WIDTH, imgHeight / divisor, null);
        Img from = Img.from(imageScale);
        HttpServletResponse response = getResponse();
        ServletOutputStream out = response.getOutputStream();
        from.write(out);
        out.close();

        response.setContentType("application/x-download");
        String fileName = URLEncoder.encode(System.nanoTime()+"test.jpg", "UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
        renderNull();
    }
}
